package com.example.cinemasystemv2.service;

import com.example.cinemasystemv2.entity.Movie;
import com.example.cinemasystemv2.repository.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MovieService {
    
    @Autowired
    private MovieRepository movieRepository;
    
    @Autowired
    private SystemLogService systemLogService;
    
    public List<Movie> getAllMovies() {
        return movieRepository.findAll();
    }
    
    public Optional<Movie> getMovieById(Long id) {
        return movieRepository.findById(id);
    }
    
    public Optional<Movie> getMovieByTitle(String title) {
        return movieRepository.findByTitle(title);
    }
    
    public List<Movie> getMoviesByDirector(String director) {
        return movieRepository.findByDirector(director);
    }
    
    public List<Movie> searchMovies(String keyword) {
        return movieRepository.searchMovies(keyword);
    }
    
    public List<Movie> searchMoviesByMultipleFields(String title, String director, String actors) {
        return movieRepository.searchMoviesByMultipleFields(title, director, actors);
    }
    
    public List<Movie> getMoviesByRating(double minRating) {
        return movieRepository.findByRatingGreaterThanEqual(minRating);
    }
    
    public Movie saveMovie(Movie movie) {
        Movie savedMovie = movieRepository.save(movie);
        systemLogService.log("电影保存: " + movie.getTitle(), "system", "SAVE_MOVIE");
        return savedMovie;
    }
    
    public Movie createMovie(String title, String director, String actors, String synopsis, int duration, double rating) {
        if (movieRepository.existsByTitle(title)) {
            throw new IllegalArgumentException("电影标题已存在");
        }
        
        Movie movie = new Movie(title, director, actors, synopsis, duration, rating);
        return saveMovie(movie);
    }
    
    public Movie updateMovie(Movie movie) {
        Movie updatedMovie = movieRepository.save(movie);
        systemLogService.log("电影更新: " + movie.getTitle(), "system", "UPDATE_MOVIE");
        return updatedMovie;
    }
    
    public void deleteMovie(Long id) {
        Optional<Movie> movieOpt = movieRepository.findById(id);
        if (movieOpt.isPresent()) {
            Movie movie = movieOpt.get();
            movieRepository.deleteById(id);
            systemLogService.log("电影删除: " + movie.getTitle(), "system", "DELETE_MOVIE");
        }
    }
    
    public boolean existsByTitle(String title) {
        return movieRepository.existsByTitle(title);
    }
    
    public long getTotalMovieCount() {
        return movieRepository.countAllMovies();
    }
}